//
//  BaseVC.swift
//  Mall-swift
//
//  Created by Bob on 2020/10/18.
//  Copyright © 2020 Bob. All rights reserved.
//

import UIKit

open class BaseVC: UIViewController {
    @IBOutlet weak var m_bottomConstraint: NSLayoutConstraint?

    open override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        configNotifications()
        
    }
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
        
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    open func initUI() {
        navigationItem.hidesBackButton = true
    }
    // MARK: - Private
    private func configNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    // MARK: - 实时刷新
    /// 开启 实时刷新 UI
    public func refreshUIRealTime() {
    #if DEBUG
    NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "INJECTION_BUNDLE_NOTIFICATION"), object: nil, queue: .main) { (note) in
        
        self.view.subviews.forEach{$0.removeFromSuperview()}
        self.viewDidLoad()
    }
    #endif
    }

    
}
// MARK: keyboard notifications
extension BaseVC {
    @objc func keyboardWillShow(notification: Notification) {
        guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }
        
        let rawFrame = value.cgRectValue
        let keyboardFrame = view.convert(rawFrame, from: nil)
        let keyboardheight = keyboardFrame.size.height
        m_bottomConstraint?.constant = keyboardheight
        UIView.animate(withDuration: 0.3) { [weak self] in
            self?.view.layoutIfNeeded()
        }
    }
    
    @objc func keyboardWillHide(notification: Notification) {
        m_bottomConstraint?.constant = CGFloat(0)
        UIView.animate(withDuration: 0.3) { [weak self] in
            self?.view.layoutIfNeeded()
        }
    }
}
